<script setup lang="ts">
import { ref, onMounted, computed, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import Request from '@/api/axios'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { SearchOutlined } from '@ant-design/icons-vue'

interface Record {
    id: string
    username: string,
    title: string
    language: string
    created_at: string
    verdict: string
    max_memory: number
    max_time: number
}

const router = useRouter()
const loading = ref(false)
const records = ref<Record[]>([])
const searchQuery = ref('')

const columns = [
    {
        title: '题目',
        dataIndex: 'title',
        width: '10%',
        ellipsis: true,
        align : 'center'
    },
    {
        title: '用户',
        dataIndex: 'username',
        width: '10%',
        align : 'center'
    },
    {
        title: '语言',
        dataIndex: 'language',
        width: '8%',
        align: 'center'
    },
    {
        title: '提交时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: '15%',
        align : 'center'
    },
    {
        title: '资源',
        dataIndex: 'resource',
        width: '12%',
        align: 'center',
    },
    {
        title: '状态',
        dataIndex: 'status',
        width: '10%',
        align: 'center'
    }
]

const fetchRecords = async () => {
    loading.value = true
    await Request.get({ url: '/record/list' }).then(res => {
        records.value = res.info.map(record => ({
            id: record.id,
            username: record.username,
            title: record.problem_title,
            language: record.language,
            created_at: record.created_at,
            user_id: record.user_id,
            verdict: record.verdict,
            max_memory: record.max_memory,
            max_time: record.max_time,
        }))
    }).catch(err => {
        message.error('获取记录失败')
        console.error(err)
    }).finally(() => {
        loading.value = false

    })

}

onMounted(fetchRecords)

const getStatusColor = (status: string) => {
    const colorMap = {
        'Accepted': '#52c41a',
        'WrongAnswer': '#f5222d',
        'TimeLimitExceeded': '#faad14',
        'RuntimeError': '#ff4d4f',
        'CompilationError': '#ffa940',
        'MemoryLimitExceeded': '#eb2f96'
    }
    return colorMap[status] || '#8c8c8c'
}

const languageIconMap = {
    'cpp': defineAsyncComponent(() => import("@/components/icons/language/CppIcon.vue")),
    'python': defineAsyncComponent(() => import("@/components/icons/language/PythonIcon.vue")),
    'java': defineAsyncComponent(() => import("@/components/icons/language/JavaIcon.vue")),
    'javascript': defineAsyncComponent(() => import("@/components/icons/language/JavaScriptIcon.vue")),
    'go': defineAsyncComponent(() => import("@/components/icons/language/GoIcon.vue")),
    'rust': defineAsyncComponent(() => import("@/components/icons/language/RustIcon.vue")),
}


const filteredRecords = computed(() => {
    const query = searchQuery.value.toLowerCase()
    return records.value.filter(record =>
        record.title.includes(query) ||
        record.username.includes(query) ||
        record.language.toLowerCase().includes(query)
    )
})
</script>

<template>
    <div class="record-list-container">
        <div class="header-container">
            <div class="search-box">
                <SearchOutlined class="search-icon" />
                <a-input-search v-model:value="searchQuery" placeholder="搜索题目、用户或语言..." />
            </div>
            <div class="record-count">
                共 {{ records.length }} 条提交记录
            </div>
        </div>

        <a-table :data-source="filteredRecords" :columns="columns" :loading="loading" :pagination="{
            showSizeChanger: true,
            showQuickJumper: true,
        }" class="custom-table">
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'title'">
                    <a-button type="link" @click="router.push({ name: 'record', params: { id: record.id } })">
                        {{ record.title }}
                    </a-button>
                </template>
                <template v-if="column.dataIndex === 'language'">
                    <component :is="languageIconMap[record.language]" />
                </template>
                <template v-if="column.dataIndex === 'time'">
                    <span class="time-cell">{{ dayjs(record.time).format('YYYY-MM-DD HH:mm:ss') }}</span>
                </template>

                <template v-if="column.dataIndex === 'status'">
                    <span class="status-tag" :style="{ backgroundColor: getStatusColor(record.verdict) }">
                        {{ record.verdict }}
                    </span>
                </template>
                <template v-if="column.dataIndex === 'resource'">
                    {{ record.max_time }} s / {{ record.max_memory }} KB
                </template>
                <template v-if="column.dataIndex === 'created_at'">
                    {{ dayjs(record.created_at).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
                <template v-if="column.dataIndex === 'username'">
                    <a-button type="link" @click="router.push({ name: 'profile', query: { uid: record.user_id } })">{{
                        record.username }} </a-button>
                </template>
            </template>
        </a-table>
    </div>
</template>

<style scoped>
.record-list-container {
    padding: 20px;
    background-color: #fff;
    min-height: 70vh;
}

.header-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-box {
    position: relative;
    width: 300px;
}

.search-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #8c8c8c;
}


.record-count {
    font-size: 14px;
}

.custom-table {
    border-radius: 8px;
    overflow: hidden;
}

.time-cell {
    font-family: 'Fira Code', monospace;
    font-size: 13px;
}

.status-tag {
    padding: 4px 12px;
    border-radius: 12px;
    color: white;
    font-size: 12px;
    display: inline-block;
    min-width: 80px;
    text-align: center;
}

:deep(.ant-table-tbody>tr>td){
    padding: 5px;
}
:deep(.ant-table-thead>tr>td){
    padding: 0;
}
:deep(.ant-table-thead>tr>th){
    padding: 4px;
}
</style>
